package amushen.module;

import amushen.base.BaseBO;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import amushen.base.DBUtil;

public class Payment extends BaseBO {
	
	public Object query(Map paras, String user, InputStream is,
			DBUtil db) {
		
		Integer contractId=getI((String)paras.get("contract_id"));
		
		List list=db.query("Payment.query", new Object[]{contractId});
		String[] head=new String[]{"id","times","value","pay_way","pay_date","remark"};
		JSONArray arr=new JSONArray();
		JSONObject obj;
		Object[] row;
		for(int i=0;i<list.size();i++){
			row=(Object[])list.get(i);
			obj=new JSONObject();
			try {
				for(int j=0;j<head.length;j++){
						obj.put(head[j], row[j]);
				}				
			} catch (JSONException e) {
				e.printStackTrace();
				return "";
			}
			arr.put(obj);
		}		
		return arr.toString();
	}
	
	public Object insert(Map paras, String user, InputStream is,
			DBUtil db) {
		Integer contract_id=getI((String)paras.get("contract_id"));
		String payWay=getS(paras.get("pay_way"));
		Double value=getD((String)paras.get("value"));
		java.util.Date payDate=getDate((String)paras.get("pay_date"));		
		String remark=getS(paras.get("remark"));
		//contract_id,value,way,pay_date,remark
		Object[] o=new Object[]{contract_id,value,payWay,payDate,remark};
		int ret=db.update("Payment.insert", o);
		if(ret==-1){
			db.rollback();
			return "Failed";
		}
		ret=db.update("Contract.updatePayment",new Object[]{contract_id});
		if(ret==-1){
			db.rollback();
			return "Failed";
		}
		db.commit();		
		return "Success";
	}
	
	public Object delete(Map paras, String user, InputStream is,
			DBUtil db) {
		Integer contract_id=getI((String)paras.get("contract_id"));
		Integer id=getI((String)paras.get("id"));		
		int ret=db.update("Payment.delete", new Object[]{id});
		if(ret==-1){
			db.rollback();
			return "Failed";
		}
		ret=db.update("Contract.updatePayment",new Object[]{contract_id});
		if(ret==-1){
			db.rollback();
			return "Failed";
		}
		db.commit();		
		return "Success";
	}
}
